package com.sfdk.io {
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.URLRequest;
import flash.utils.ByteArray;

public class UploadHelper extends EventDispatcher {
    private var fileLocation_:String;
    private var uploadQueue_:Vector.<Object>;
    private var uploadInProgress_:Boolean;

    public function UploadHelper() {
        uploadQueue_ = new Vector.<Object>();
    }

    private function onIoError(e:IOErrorEvent):void {
        trace("Cannot save " + fileLocation_);
        completeHandler(null);
    }

    public function writeXML(xmlData:XML, fileName:String, uploadPath:String):void {
        try {
            var file:File = File.createTempFile();
            trace(file.nativePath);
        }
        catch(e:IOErrorEvent) {
            trace("toto");
        }
        var stream:FileStream = new FileStream();

        var str:String = "<?xml version=\"1.0\"?>\n" + xmlData.toXMLString();
        str = str.replace(/\r/g, "\n");
        str = str.replace(/\n/g, File.lineEnding);

        stream.open(file, FileMode.WRITE);
        stream.writeUTFBytes(str);
        stream.close();

        addToUploadQueue(file, fileName, uploadPath + "upload.php");
    }

    private function completeHandler(e:Event):void {
        //PopUpManager.removePopUp(uploadProgress_);
        var uploadObject:Object = uploadQueue_.pop();
        if (uploadObject == null) {
            uploadInProgress_ = false;
            dispatchEvent(new Event(Event.COMPLETE));
        } else {
            upload(uploadObject.file, uploadObject.name, uploadObject.path);
        }
    }

    public function writePNG(pngImg:ByteArray, fileName:String, uploadPath:String):void {
        var file:File = File.createTempFile();
        var stream:FileStream = new FileStream();

        stream.open(file, FileMode.WRITE);
        stream.writeBytes(pngImg);
        stream.close();

        addToUploadQueue(file, fileName, uploadPath + "upload.php");
    }

    private function addToUploadQueue(file:File, fileName:String, uploadPath:String):void {
        if (uploadInProgress_) {
            uploadQueue_.push({file : file, name : fileName, path : uploadPath});
        } else { // C'est le seul element donc on lance l'upload
            upload(file, fileName, uploadPath);
        }
    }

    public function upload(file:File, fileName:String, uploadPath:String):void {
        uploadInProgress_ = true;
        var request:URLRequest = new URLRequest(uploadPath + "?name=" + fileName);

        //file.addEventListener(ProgressEvent.PROGRESS, progressHandler);
        file.addEventListener(Event.COMPLETE, completeHandler);
        file.addEventListener(IOErrorEvent.IO_ERROR, onIoError);

        file.upload(request);
    }
}
}